<template>
  <div class="login-page">
    <van-nav-bar
      title="账号登录"
      @click-left="$router.back()"
      left-text=""
      left-arrow
    />
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="username"
        placeholder="请输入账号"
        :rules="[
          { required: true, message: '请填写用户名' },
          { pattern: /^\w{5,}/, message: '用户名至少为5位' },
        ]"
      />
      <!-- rules 规则 [ pattern 标准, message 提示信息 ]-->
      <van-field
        v-model="password"
        type="password"
        name="password"
        placeholder="请输入密码"
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: /^\w{6,}/, message: '密码至少为6位' },
        ]"
      />
      <div style="margin: 16px">
        <van-button block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
    <div class="register">
      <router-link class="link" to="/register">还没有账号，去注册~</router-link>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/user'
import { setToken } from '@/utils/storage'
export default {
  name: 'login-page',
  data () {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    async onSubmit (value) {
      const data = await login(value)
      console.log(data)
      setToken(data.body.token)
      this.$toast.success(data.description)
      this.$router.push('/user')
    }
  }
}
</script>

<style lang="less" scoped>
.register {
  margin-top: 30px;
  text-align: center;
  .link {
    color: #666;
    font-size: 14px;
  }
}
</style>
